package com.jgzx.security.advice;

import com.jgzx.security.annotation.PortalDecrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * 请求平台参数解密AOP
 * @author libo
 * @date 2021/7/30 20:15
 */
@Slf4j
@RestControllerAdvice
public class PortalDecryptRequestAdvice implements RequestBodyAdvice {

    private boolean encrypt;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(PortalDecrypt.class)) {
            encrypt = true;
        } else {
            encrypt = false;
        }
        return encrypt;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        if (encrypt) {
            try {
                return new PortalDecryptHttpInputMessage(inputMessage);
            } catch (Exception e) {
                log.error("解密错误", e);
            }
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
